﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Collections;
using System.ComponentModel;
using System.Collections.Specialized;

namespace CaliburnWpf.Views.Infrastructure
{
    /*
     *automatically wraps objects when binding to data context and unwraps them when getting values
     *generated wrappers are stored in identityMap  
     */

    public class WrapConverter : IValueConverter
    {
        public Hashtable identityMap = new Hashtable();

        public static bool s_is_design=false;
        public static Hashtable s_identityMap = new Hashtable();

        public WrapConverter():this(s_identityMap)
        {
            
        }
        public WrapConverter(Hashtable vm)
        {
            this.identityMap = vm;
        }


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (s_is_design ||value is INotifyPropertyChanged|| value is INotifyable || value is INotifyableCollection || value is INotifyCollectionChanged) {
                return value;
            }


            var existing = identityMap[value];
            
            
            if (existing==null)
            {
                if (value is IEnumerable)
                    existing = new NotifyableCollectionWrapper(value as IEnumerable);
                else
                    existing = new DynamicNotifyableWrapper(value);
                identityMap[value] = existing;
            }
            return existing;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var wrapper = value as IWrapper;
            return wrapper.Instance;
        }

    }
}
